
import sys,os,threading
import optparse

import pathlib
toolnameRaw = pathlib.Path(__file__).absolute().parts[-1]
toolname = toolnameRaw[2:-5]

def match(optionList,typein):
    posibleList = optionList
    pointer = 0
    def compare(Aposible):
        return len(Aposible)>pointer and typein[pointer] == Aposible[pointer]
#
    while(len(typein) > pointer):
        posibleList = list(filter(compare, posibleList))
        pointer += 1
    return list(posibleList)


class Acmd(threading.Thread):
    def __init__(self, cmdArg):
        threading.Thread.__init__(self)
        self.cmdArg = cmdArg
        
    def run(self):
        os.system(self.cmdArg)

def operate_cmd(arg):
    status["threadList"].append(Acmd(arg))
    status["threadList"][-1].start()

def operate_list(arg):
    for athread in status["threadList"]:
        print(athread.getName(), athread.cmdArg)
    print()
    
def operate_kill(arg):
    if(arg[:6] == "lambda"):
        tfilter = eval(arg)
#        status["threadList"] = list(filter(lambda x: not tfilter(x), status["threadList"]))
        delCount = 0
        for ind in range(len(status["threadList"])):
            if(tfilter([ind-delCount].cmdArg)):
                del status["threadList"][ind-delCount]
                delCount+=1
                # 中断命令？
    else:
        index = int(arg) -1
        if(index < len(status["threadList"])):
            del status["threadList"][index]
        else: operate_list(0)

def operate_exit(arg):
    status["isRunning"] = False

threadList = []
operateList = filter(lambda x:x[:8] == "operate_",list(locals().keys()))
operateList = list(map(lambda x:x[8:], operateList))

status = {
    "threadList" : [],
    "isRunning" : True
}


def func(isHelp=False):
    if(isHelp):
        return [toolname,"... | ~ %s"%(toolname), '#multi command line' , '-h']
    parser = optparse.OptionParser("")
    parser.add_option("-c",  '--startCmd', dest="startCmd", default = '')
    options, args = parser.parse_args()
    try:
        if(len(options.startCmd)):
            operate_cmd(options.startCmd)
        while(status["isRunning"]):
            rawInput = input().split()
            if(len(rawInput)==0):continue
#
            arguments = [rawInput[0]," ".join(rawInput[1:])]
            posibleChoise = match(operateList, arguments[0])
            if(len(posibleChoise) == 1):
                eval("operate_" + posibleChoise[0])(arguments[1])
    except Exception as e:
        print(e)
        print("="*8 + " Exit " + "="*8)

